import 'package:flutter/material.dart';
import 'package:example/base/custom_dialog.dart';
import 'package:example/config/color_config.dart';
import 'package:example/utils/dialog_ext.dart';
import 'package:example/widget/my_image.dart';
import 'package:example/widget/none_scroll_behavior.dart';
import 'package:example/widget/primary_btn.dart';
import 'package:get/get.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../../utils/common.dart';

class SheetDialog<T> extends CustomDialog<SheetDialogController<T>> {
  SheetDialog({
    SheetDialogController<T>? controller,
    List<T>? list,
    T? selectItem,
    String title = "",
    String Function(T item)? textBuilder,
    bool Function(T item, T? select)? selectBuilder,
    VoidCallback? cancel,
    double? maxHeight,
    Function(T t)? confirm,
  }) : super(
            SheetDialogController<T>(
                list: list,
                selectItem: selectItem,
                title: title,
                textBuilder: textBuilder,
                selectBuilder: selectBuilder,
                cancel: cancel,
                confirm: confirm,
                maxHeight: maxHeight),
            externalController: controller) {
    if (controller != null) {
      controller.list = controller.list ?? list;
      controller.selectItem = controller.selectItem ?? selectItem;
      controller.title = controller.title ?? title;
      controller.textBuilder = controller.textBuilder ?? textBuilder;
      controller.selectBuilder = controller.selectBuilder ?? selectBuilder;
      controller.cancel = controller.cancel ?? cancel;
      controller.confirm = controller.confirm ?? confirm;
    }
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
      int index = initController.list?.indexWhere((item) {
            return initController.selectBuilder
                    ?.call(item, initController.selectItem) ??
                initController.selectItem != null &&
                    initController.selectItem == item;
          }) ??
          0;
      if (index < 0) {
        index = 0;
      }
      double extent = 50.w * index;
      if (initController.scrollController.hasClients &&
          extent > initController.scrollController.position.maxScrollExtent) {
        extent = initController.scrollController.position.maxScrollExtent;
      }
      if (initController.scrollController.hasClients) {
        initController.scrollController.jumpTo(extent);
      }
    });
  }

  @override
  Widget initView(BuildContext context, SheetDialogController<T> controller) {
    return Stack(
      children: [
        Positioned(
          bottom: 0,
          left: 0,
          right: 0,
          child: Container(
            constraints: BoxConstraints(
                maxHeight: controller.maxHeight ?? screenHeight() / 2),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.vertical(top: Radius.circular(12.r)),
            ),
            child: SafeArea(
              top: false,
              child: _body(context, controller),
            ),
          ),
        ),
      ],
    );
  }

  _body(BuildContext context, SheetDialogController<T> controller) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: [
        // _title(controller),
        Divider(
          color: ColorConfig.FFF0F0F0,
          thickness: 0.5,
          indent: 10.w,
          endIndent: 10.w,
        ),
        Flexible(child: _content(controller)),
      ],
    );
  }

  _title(SheetDialogController<T> controller) {
    return SizedBox(
      height: 58.w,
      child: Row(
        children: [
          GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () {
              hide();
            },
            child: Padding(
              padding: EdgeInsets.symmetric(horizontal: 14.w, vertical: 23.w),
              child: MyImage(
                path: "assets/svg/ic_close.svg",
                width: 12.w,
              ),
            ),
          ),
          Expanded(
            child: Text(
              controller.title ?? "",
              textAlign: TextAlign.center,
              style: TextStyle(
                color: ColorConfig.FF020306,
                fontSize: 17.sp,
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
          SizedBox(width: 41.w),
        ],
      ),
    );
  }

  _content(SheetDialogController<T> controller) {
    return ScrollConfiguration(
      behavior: NoneScrollBehavior(),
      child: SingleChildScrollView(
        controller: controller.scrollController,
        physics: const ClampingScrollPhysics(),
        child: ListView.builder(
          controller: ScrollController(keepScrollOffset: false),
          padding:  EdgeInsets.only(bottom: 20.w),
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
          itemCount: controller.list?.length ?? 0,
          itemBuilder: (BuildContext context, int index) {
            var item = controller.list![index];
            bool isSelect = controller.selectBuilder
                    ?.call(item, controller.selectItem) ??
                controller.selectItem != null && controller.selectItem == item;
            String text =
                controller.textBuilder?.call(item!) ?? item.toString();
            return Stack(
              children: [
                PrimaryBtn(
                  width: double.infinity,
                  height: 50.w,
                  text: text,
                  textColor: isSelect ? ColorConfig.dark_app_main : ColorConfig.text,
                  background: Colors.transparent,
                  fontSize: 16.sp,
                  fontWeight: FontWeight.w500,
                  onTap: () {
                    hide();
                    controller.confirm?.call(item!);
                  },
                ),
                Positioned(
                  right: 22.w,
                  child: Visibility(
                    visible: isSelect,
                    child: Container(
                      height: 50.w,
                      alignment: Alignment.center,
                      child: MyImage(
                        path: "assets/svg/ic_hook.svg",
                        width: 14.w,
                      ),
                    ),
                  ),
                ),
              ],
            );
          },
          // separatorBuilder: (BuildContext context, int index) {
          //   return Divider(
          //     height: index == (list?.length ?? 0) - 1 ? 5.w : 1.w,
          //   );
          // },
        ),
      ),
    );
  }
}

class SheetDialogController<T> extends GetxController {
  List<T>? list;
  T? selectItem;
  String? title;
  double? maxHeight;
  String Function(T item)? textBuilder;
  bool Function(T item, T? select)? selectBuilder;
  VoidCallback? cancel;
  Function(T t)? confirm;
  final ScrollController scrollController = ScrollController();

  SheetDialogController({
    this.list,
    this.selectItem,
    this.title,
    this.textBuilder,
    this.selectBuilder,
    this.cancel,
    this.maxHeight,
    this.confirm,
  });
}
